﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Linq;
using System.Threading;
using OauthProvider;

namespace Chat_WebServer.Controllers
{
    public class OAuthMessageController : ApiController
    {
        private static IOAuthProvider provider;

        public OAuthMessageController()
        {
            var consumerStore = new ConsumerStore();
            SimpleTokenStore tokenStore = new SimpleTokenStore();
            provider = new OAuthProvider(tokenStore,
                                   new ConsumerValidationInspector(consumerStore),
                                   new OAuth10AInspector(tokenStore));
        }

        // Lay tin nhan theo ten
        public List<string> Get()
        {
            IOAuthContext context = new OAuthContextBuilder().FromUri(HttpMethod.Get.ToString(), Request.RequestUri);
            try
            {
                provider.AccessProtectedResourceRequest(context);

                var accessToken = (MiniAccessToken)TokenUtility.GetToken(context.Token, TokenType.Access);

                string username = accessToken.UserName;
                int count = 0;
                List<string> messages = new List<string>();
                while (count < 30)
                {
                    messages = GetMessagesByUsername(username);
                    if (messages.Count > 0)
                        return messages;
                    else
                        Thread.Sleep(1000);
                    count++;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return null;
        }

        // Lay tin nhan theo ten
        private List<string> GetMessagesByUsername(string username)
        {
            using (var db = new AccountEntities())
            {
                List<string> messages = new List<string>();
                var user = db.Messages.ToList().FirstOrDefault(a => a.UserName == username);
                XElement xMessages = XElement.Parse(user.Messages);
                foreach (XElement fromUser in xMessages.Elements())
                {
                    foreach (XElement message in fromUser.Elements())
                    {
                        if (message.Attribute("new").Value == "1")
                        {
                            message.Attribute("new").Value = "0";
                            messages.Add(fromUser.Attribute("name").Value + "@" + message.Attribute("mess").Value);
                        }
                    }
                }
                if (messages.Count > 0)
                {
                    user.Messages = xMessages.ToString();
                    db.SaveChanges();
                }
                return messages;
            }
        }

        // Gui tin nhan
        public HttpStatusCode POST([FromBody]string mess)
        {
            IOAuthContext context = new OAuthContextBuilder().FromUri(HttpMethod.Get.ToString(), Request.RequestUri);
            try
            {
                provider.AccessProtectedResourceRequest(context);

                var accessToken = (MiniAccessToken)TokenUtility.GetToken(context.Token, TokenType.Access);

                string fromUser = accessToken.UserName;
                using (var db = new AccountEntities())
                {
                    //Tao element cho message
                    XElement message = new XElement("message");
                    message.SetAttributeValue("new", "1");
                    message.SetAttributeValue("mess", mess);

                    // Tim trong database
                    var user = db.Messages.ToList().FirstOrDefault(a => a.UserName == context.QueryParameters["toUser"].ToString());
                    XElement xMessages = XElement.Parse(user.Messages);

                    // Them message vao database neu co san nguoi gui
                    foreach (XElement fromuser in xMessages.Elements())
                    {
                        if (fromuser.Attribute("name").Value == fromUser)
                        {
                            fromuser.Add(message);
                            user.Messages = xMessages.ToString();
                            db.SaveChanges();
                            return HttpStatusCode.OK;;
                        }
                    }

                    // Tao element cho nguoi gui
                    XElement friend = new XElement("friend");
                    friend.SetAttributeValue("name", fromUser);

                    //Them message
                    friend.Add(message);

                    //Them nguoi gui
                    xMessages.Add(friend);

                    //Luu vao database
                    user.Messages = xMessages.ToString();
                    db.SaveChanges();
                    return HttpStatusCode.OK;
                }
            }
            catch (Exception ex)
            {
                return HttpStatusCode.NotImplemented;
            }
        }
    }
}
